package top.hekun.study.core.visitor.method.simple;

import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.commons.AdviceAdapter;

import static org.objectweb.asm.Opcodes.GETSTATIC;
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;

/**
 * @Author: 贺坤
 * @Date: 2023/5/10 10:16
 */
public class MyMethodVisitor3 extends MethodVisitor {
    private String thisClassName = this.getClass().getSimpleName();

    protected MyMethodVisitor3(int api, MethodVisitor methodVisitor) {
        super(api, methodVisitor);
    }

    @Override
    public void visitCode() {
        System.out.println(thisClassName + ":visitCode");
        super.visitCode();
        visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
        visitLdcInsn(thisClassName + "在执行 test1()V 方法前 添加输入语句");
        visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false);


    }

    @Override
    public void visitInsn(int opcode) {
//        System.out.println(thisClassName + ":visitInsn --- ");
        if (opcode == Opcodes.ATHROW || (opcode >= Opcodes.IRETURN && opcode <= Opcodes.RETURN)) {
            System.out.println(thisClassName + ":visitInsn --- 执行返回前添加代码 ");
            visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
            visitLdcInsn(thisClassName + "在 test1()V 返回前 添加输入语句");
            visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false);
        }
        super.visitInsn(opcode);
    }
}
